Global Error Handling
There are two pages for global error handling
- Root level
error.tsx
. This file will handle errors on any component in the subtree through an error boundary. It does not catch any error in root levellayout.tsx
andpage.tsx
. - Root level
global-error.tsx
. It behaves as its own standalone page (need its own html and body tags) and it is displayed as fallback when an error occurs inlayout.tsx
orpage.tsx
.
Next.js documentation: source
How to validate it
NOTICE: File global-error.tsx
can only be tested in a production build. You need to run the app with pnpm run build && pnpm run start
.
NOTE: An utility component called Error
was added to help testing this feature. You can find it under src/dev-utils/components/Error
.
- Add the
Error
component in the component tree where you want to trigger the error. - Run the app locally.
- You'll see a button Throw Error being rendered by the
Error
component. If you press the button, it will cause an error in next.js causing it to show an error handler screen.
- Using the
Error
component in the rootlayout.tsx
or rootpage.tsx
will cause to displayglobal-error.tsx
if you are running a production build. - Using the
Error
component anywhere else in the subtree will cause an error that will call root levelerror.tsx
(only if not caught by a more specificerror.tsx
in the subtree).
Screenshots
Page error.tsx
Page global-error.tsx